package com.appkubes.mall.admin.application.order.order.service;

import com.appkubes.common.utils.data.date.DateUtils;
import com.appkubes.common.utils.data.string.UUIDUtils;
import com.appkubes.mall.admin.application.order.order.dao.CollectRecordsDao;
import com.appkubes.mall.admin.application.order.order.entity.model.CollectRecordsResult;
import com.appkubes.mall.core.po.MallCollectedRecords;
import com.appkubes.mall.core.po.MallCollectedRecordsExample;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
public class CollectRecordsService {
    @Autowired
    CollectRecordsDao collectRecordsDao;

    public int add(MallCollectedRecords model) {
        model.setCollectedRecordsKey(UUIDUtils.getUUID());
        model.setCreateTime(DateUtils.DateToTimestamp(new Date()));
        model.setUpdateTime(DateUtils.DateToTimestamp(new Date()));
        model.setOrderNo(DateUtils.parseDateToStr(new Date(), DateUtils.DATE_TIME_FORMAT_YYYYMMDDHHMISSSSS) + "" + (int) ((Math.random() * 9 + 1) * 10000));
        model.setAppKey(null);
        return collectRecordsDao.insertSelective(model);
    }

    public PageInfo querySelective(String appKey, String orderKey, Integer page, Integer size, String sort, String order) {
        MallCollectedRecordsExample example = new MallCollectedRecordsExample();
        MallCollectedRecordsExample.Criteria criteria = example.createCriteria();
        if (!StringUtils.isEmpty(appKey)) {
            criteria.andAppKeyEqualTo(appKey);
        }
        if (!StringUtils.isEmpty(sort) && !StringUtils.isEmpty(order)) {
            example.setOrderByClause(sort + " " + order);
        }
        criteria.andOrderKeyEqualTo(orderKey);
        PageHelper.startPage(page, size);
        List<MallCollectedRecords> list = collectRecordsDao.selectByExample(example);
        PageInfo pageInfo = new PageInfo(list);
        return pageInfo;
    }

    public PageInfo getList(String queryStr, int page, int limit) {
        List<CollectRecordsResult> list = collectRecordsDao.getList(queryStr, (page - 1) * limit, limit, false);
        PageInfo pageInfo = new PageInfo(list);
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(limit);
        int count = 0;
        List<CollectRecordsResult> totalList = collectRecordsDao.getList(queryStr, 0, 0, true);
        if (totalList != null) count = totalList.get(0).getTotal();
        pageInfo.setTotal(count);
        return pageInfo;
    }
}
